<template>
  <el-dialog 
    :title="title" 
    v-model="dialogVisible" 
    width="500px" 
    destroy-on-close 
    @close="handleClose"
  >
    <el-form ref="formRef" :model="form" :rules="rules" label-width="100px">
      <el-form-item label="快捷选择">
        <el-select 
          v-model="selectedLang" 
          placeholder="请选择语言" 
          filterable 
          @change="handleQuickSelect"
        >
          <el-option
            v-for="(lang, code) in languages"
            :key="code"
            :label="`${lang.zhName} (${lang.enName})`"
            :value="code"
          >
            <span>{{ lang.zhName }}</span>
            <span class="text-gray-500 ml-2">({{ lang.enName }})</span>
          </el-option>
        </el-select>
      </el-form-item>
      <el-form-item label="语言名称" prop="name">
        <el-input v-model="form.name" placeholder="请输入语言名称" />
      </el-form-item>
      <el-form-item label="语言代码" prop="code">
        <el-input v-model="form.code" placeholder="请输入语言代码" />
      </el-form-item>
      <el-form-item label="图标" prop="icon">
        <el-upload
          class="avatar-uploader"
          :action="uploadUrl"
          :headers="headers"
          :show-file-list="false"
          :on-success="handleUploadSuccess"
        >
          <img v-if="form.icon" :src="form.icon" class="avatar" />
          <el-icon v-else class="avatar-uploader-icon"><Plus /></el-icon>
        </el-upload>
      </el-form-item>
      <el-form-item label="排序" prop="sort">
        <el-input-number v-model="form.sort" :min="0" :max="999" />
      </el-form-item>
      <el-form-item label="状态">
        <el-switch v-model="form.status" :active-value="1" :inactive-value="0" />
      </el-form-item>
      <el-form-item label="默认语言">
        <el-switch v-model="form.is_default" :active-value="1" :inactive-value="0" />
      </el-form-item>
    </el-form>
    <template #footer>
      <el-button @click="handleClose">取消</el-button>
      <el-button type="primary" @click="handleSubmit" :loading="loading">确定</el-button>
    </template>
  </el-dialog>
</template>

<script setup lang="ts">
import { ref, reactive, computed, watch } from 'vue'
import type { FormInstance } from 'element-plus'
import { ElMessage } from 'element-plus'
import { Plus } from '@element-plus/icons-vue'
import { addLanguage, editLanguage } from '/@/api/language'
import type { Language, LanguageForm } from '/@/types/language'
import { useUserStore } from '/@/store/modules/user'
import { useAclStore } from '/@/store/modules/acl'
import { languages } from '../data/languages.ts'

const props = defineProps<{
  visible: boolean
  type: 'add' | 'edit'
  currentRow?: Language | null
}>()

const emit = defineEmits(['update:visible', 'success'])

const dialogVisible = computed({
  get: () => props.visible,
  set: (val) => emit('update:visible', val)
})

const title = computed(() => props.type === 'add' ? '新增语言' : '编辑语言')

const loading = ref(false)
const formRef = ref<FormInstance>()

// 默认表单数据
const defaultForm: LanguageForm = {
  name: '',
  code: '',
  icon: '',
  sort: 0,
  status: 1,
  is_default: 0
}

const form = reactive<LanguageForm>({ ...defaultForm })

// 表单校验规则
const rules = {
  name: [
    { required: true, message: '请输入语言名称', trigger: 'blur' }
  ],
  code: [
    { required: true, message: '请输入语言代码', trigger: 'blur' }
  ],
  icon: [
    { required: true, message: '请上传图标', trigger: 'change' }
  ]
}

// 上传相关
const userStore = useUserStore()
const uploadUrl = `${import.meta.env.VITE_APP_BASE_URL}/admin/upload`
const headers = {
  Authorization: userStore.token
}

const aclStore = useAclStore()

const selectedLang = ref('')

// 初始化表单数据
const initFormData = () => {
  if (props.type === 'edit' && props.currentRow) {
    Object.assign(form, props.currentRow)
  } else {
    Object.assign(form, defaultForm)
  }
}

// 上传成功回调
const handleUploadSuccess = (res: any) => {
  form.icon = res.data.url
}

// 处理提交
const handleSubmit = async () => {
  // 检查权限
  if (props.type === 'add' && !aclStore.getPermission.includes('system:language:doAdd')) {
    return
  }
  if (props.type === 'edit' && !aclStore.getPermission.includes('system:language:doEdit')) {
    return
  }

  if (!formRef.value) return
  await formRef.value.validate(async (valid) => {
    if (valid) {
      loading.value = true
      try {
        if (props.type === 'add') {
          await addLanguage(form)
          ElMessage.success('新增成功')
        } else if (props.currentRow) {
          await editLanguage(props.currentRow.language_id, form)
          ElMessage.success('更新成功')
        }
        emit('success')
        handleClose()
      } catch (error) {
        console.error('提交失败:', error)
      } finally {
        loading.value = false
      }
    }
  })
}

// 处理关闭
const handleClose = () => {
  dialogVisible.value = false
  formRef.value?.resetFields()
  selectedLang.value = ''
}

// 监听visible变化
watch(() => props.visible, (val) => {
  if (val) {
    initFormData()
  }
})

// 处理快捷选择
const handleQuickSelect = (code: string) => {
  const lang = languages[code]
  if (lang) {
    form.name = lang.zhName
    form.code = lang.code
    // 使用语言的排序值
    form.sort = lang.sort
  }
  selectedLang.value = '' // 重置选择
}
</script>

<style lang="scss" scoped>
.avatar-uploader {
  :deep(.el-upload) {
    border: 1px dashed #d9d9d9;
    border-radius: 4px;
    cursor: pointer;
    position: relative;
    overflow: hidden;
    transition: var(--el-transition-duration-fast);

    &:hover {
      border-color: var(--el-color-primary);
    }
  }
}

.avatar-uploader-icon {
  font-size: 28px;
  color: #8c939d;
  width: 80px;
  height: 80px;
  text-align: center;
  line-height: 80px;
}

.avatar {
  width: 80px;
  height: 80px;
  display: block;
}

:deep(.el-select-dropdown__item) {
  display: flex;
  justify-content: space-between;
  align-items: center;
}
</style> 